package com.algorithm;

/**
 * @author: sun.hongliang
 * @create: 2019/07/01 11:53
 */
public class ListNodeTest {
    public static void main(String[] args) {
        final ListNode head = initListNode();
        ListNode t = new ListNode(3);
        addListNode(head, t);
        LinkListPrint.printListNode(head);
        ListNode t2 = new ListNode(4);
        addListNodeByIndex(head, t2, 1);
        LinkListPrint.printListNode(head);
        removeNthFromEnd(head, 1);
        LinkListPrint.printListNode(head);
    }

    public static ListNode initListNode() {
        ListNode head = new ListNode(0);
        ListNode one = new ListNode(1);
        ListNode two = new ListNode(2);
        head.next = one;
        one.next = two;
        return head;
    }

    public static void addListNode(ListNode head, ListNode temp) {
        ListNode p = head;
        while (p.next != null) {
            p = p.next;
        }
        p.next = temp;
    }

    public static void addListNodeByIndex(ListNode head, ListNode temp, int index) {
        ListNode p = head;
        int j = 0;
        while (p.next != null && j < index - 1) {
            p = p.next;
            j++;
        }
        temp.next = p.next;
        p.next = temp;
    }

    public static void deleteListNodeByIndex(ListNode head, int index) {
        ListNode p = head;
        int j = 0;
        while (p.next != null && j < index) {
            p = p.next;
            j++;
        }
        if (p.next == null) {
            System.out.println("index 错误");
            return;
        }
        ListNode t = p.next;
        p.next = p.next.next;
        t.next = null;
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode p = pre;
        ListNode q = pre;
        int i = 0;
        while (p.next != null) {
            if (i >= n) {
                q = q.next;
            }
            p = p.next;
            i++;
        }
        ListNode t = q.next;
        q.next = q.next.next;
        t.next = null;
        return pre.next;
    }
}
